#include "OcmfServer.h"

OcmfServer::OcmfServer()
{
    //initialize variables
    dbPingInterval = 500;   //db loop operates every half second
    aborted = false;        //allows the server thread to loop

    //start the server
    start(LowestPriority);
}

//runs the server on a separate thread
void OcmfServer::run()
{
    //loop until signaled
    forever
    {
        //check for aborted flag
        threadLocker.lock();
        if(aborted)return;
        threadLocker.unlock();

        //check database for scheduled experiments for this server instance
        QQueue<Experiment*> * experimentSchedule = dbClient.GetScheduledExperiments(serverId);

        //iterate over all experiments returned by the database
        while(experimentSchedule->count() > 0)
        {
            //get the head of the queue
            Experiment * experiment = experimentSchedule->at(0);

            //pop experiment from the head of the queue
            experimentSchedule->pop_front();

            //set the status of the server in the database
            dbClient.SetServerStatus(serverId, Running, experiment);

            //get the experiment at the head of the queue, run and then add to database
            dbClient.AddExperimentResult(runExperiment(experiment));

            //delete the experiment
            delete experiment;
        }
        
        //delete the queue - dynamically allocated within the dbClient
        delete experimentSchedule;

        //clear the status of the server in the database
        dbClient.SetServerStatus(serverId, Idle, NULL);

        //sleep for designated period e.g. 1 min
        sleep(dbPingInterval);
    }
}

void OcmfServer::Abort()
{
    threadLocker.lock();
    aborted = true;
    threadLocker.unlock();
}
